# -*- coding: utf-8 -*-
# @Author   : zxc19
# @Time     : 2023/7/6 20:48
# @FileName : send_email.py
# @Desc     : 请输入功能模块描述
import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from pathlib import Path
from typing import List

from loguru import logger

from config import settings


class EmailSender:
    def __init__(self, email: str = settings.EMAIL_USER, password: str = settings.EMAIL_USER_PASSWORD,
                 smtp_server: str = settings.EMAIL_SMTP_SERVER, smtp_port: int = settings.EMAIL_SMTP_PORT):
        """
        初始化方法，设置必要的参数，默认从配置文件读取
        :param email: 邮件发件人邮箱
        :param password: 发件人邮箱密码
        :param smtp_server: SMTP 服务器地址
        :param smtp_port: SMTP 服务器端口，默认为 25
        """
        self.email = email
        self.password = password
        self.smtp_server = smtp_server
        self.smtp_port = smtp_port

    def send_email(self, to_email: str | List[str], subject: str, content: str, cc_email: str | List[str] = None,
                   attachment: str | Path | List[str | Path] = None):
        """
        发送电子邮件的方法
        :param to_email: 收件人的电子邮件地址，可以是一个字符串或字符串列表
        :param subject: 邮件主题
        :param content: 邮件正文
        :param cc_email: 抄送收件人的电子邮件地址，可以是一个字符串或字符串列表
        :param attachment: 附件的文件路径，可以是一个字符串或字符串列表
        :return: 是否发送成功
        """
        # 创建一个 MIMEMultipart 对象来存储邮件内容
        msg = MIMEMultipart()

        # 设置邮件主题和发件人、收件人、抄送收件人的电子邮件地址
        msg['Subject'] = subject
        msg['From'] = self.email
        msg['To'] = to_email if isinstance(to_email, str) else ', '.join(to_email)
        if cc_email:
            msg['Cc'] = cc_email if isinstance(cc_email, str) else ', '.join(cc_email)

        # 将邮件正文添加到 MIMEMultipart 对象中
        msg.attach(MIMEText(content, 'plain'))

        # 添加附件
        if attachment:
            if isinstance(attachment, List):
                for attach in attachment:
                    attach = Path(attach)
                    part = MIMEApplication(open(attach, 'rb').read())
                    part.add_header('Content-Disposition', 'attachment', filename=attach.name)
                    msg.attach(part)
            if isinstance(attachment, str | Path):
                attachment = Path(attachment)
                part = MIMEApplication(open(attachment, 'rb').read())
                part.add_header('Content-Disposition', 'attachment', filename=attachment.name)
                msg.attach(part)

        # 使用 SMTP 进行邮件发送
        try:
            logger.debug(f'准备发送邮件: 发件人【{self.email}】,收件人【{to_email}】,抄送【{cc_email}】')
            with smtplib.SMTP(self.smtp_server, self.smtp_port) as smtp:
                smtp.login(self.email, self.password)
                to_emails = to_email if isinstance(to_email, list) else [to_email]
                cc_emails = cc_email if isinstance(cc_email, list) else []
                smtp.sendmail(self.email, to_emails + cc_emails, msg.as_string())
                logger.info(f'发送邮件成功: 发件人【{self.email}】,收件人【{to_email}】,抄送【{cc_email}】')
                return True
        except Exception as e:
            logger.error(f'邮件发送失败===>{e}')
            return False


if __name__ == '__main__':
    sender = EmailSender('zxc@soul.com', 'admin@dptech123', '10.121.110.248', 25)
    # sender = EmailSender('my_prayers@163.com', 'RWQBLBVTKGJCJTUR', 'smtp.163.com', 25)
    sender.send_email(['zxc@soul.com', 'dky@soul.com'], 'py工具测试ss', '发送d了')
    # sender.send_email(['444455432@qq.com'], 'py工具测试', '发送了', attachment=['./__init__.py'])
